﻿using LuShanTea.IService;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LuShanTea.DTO;
using LuShanTea.Service.Entities;
using System.Data.Entity;

namespace LuShanTea.Service
{
    public class AddressService : IAddressService
    {
        private AddressDTO ToDTO(Address en)
        {
            AddressDTO dto = new AddressDTO();
            dto.Adress = en.ReciverAddress;
            dto.AreaId = en.AreaId;
            dto.AreaName = en.Area.Name;
            dto.CityId = en.Area.CityId;
            dto.CityName = en.Area.City.Name;
            dto.CreateDateTime = en.CreateDateTime;
            dto.Id = en.Id;
            dto.PhoneNum = en.PhoneNum;
            dto.PostEmail = en.PostEmail;
            dto.ProvinceId = en.Area.City.ProId;
            dto.ProvinceName = en.Area.City.Province.Name;
            dto.ReciverName = en.ReciverName;
            dto.UserId = en.UserId;
            dto.UserName = en.User.Name;
            return dto;
        }

        public long AddNew(AddressAddNewDTO addressA)
        {
            Address en = new Address();
            en.AreaId = addressA.AreaId;
            en.PhoneNum = addressA.PhoneNum;
            en.PostEmail = addressA.PostEmail;
            en.ReciverAddress = addressA.ReciverAddress;
            en.ReciverName = addressA.ReciverName;
            en.UserId = addressA.UserId;
            using (LuShanTeaContext ctx = new LuShanTeaContext())
            {
                ctx.Address.Add(en);
                ctx.SaveChanges();
                return en.Id;
            }
        }

        public int GetAddressByUserCount(long userId)
        {
            using (LuShanTeaContext ctx = new LuShanTeaContext())
            {
                BaseService<User> bsUser = new BaseService<User>(ctx);
                var user = bsUser.GetById(userId);
                if (user == null)
                {
                    throw new ArgumentException("参数异常，找不到Id=" + userId + "的用户");
                }
                BaseService<Address> bs = new BaseService<Address>(ctx);
                return bs.GetAll().Where(a => a.UserId == userId).Count();
            }
        }

        public AddressDTO[] GetAddressByUserId(long userId)
        {
            using (LuShanTeaContext ctx = new LuShanTeaContext())
            {
                BaseService<User> bsUser = new BaseService<User>(ctx);
                var user = bsUser.GetById(userId);
                if (user == null)
                {
                    throw new ArgumentException("参数异常，找不到Id=" + userId + "的用户");
                }
                BaseService<Address> bs = new BaseService<Address>(ctx);
                return bs.GetAll().AsNoTracking()
                      .Include(e => e.User)
                      .Include(e => e.Area)
                      .Include(e => e.Area.City)
                      .Include(e => e.Area.City.Province)
                      .Where(e => e.UserId == userId).ToList().OrderByDescending(a => a.CreateDateTime).Select(e => ToDTO(e)).ToArray();
            }
        }

        public long? GetFirstAddressIdByUserId(long userId)
        {
            using (LuShanTeaContext ctx = new LuShanTeaContext())
            {
                BaseService<User> bsUser = new BaseService<User>(ctx);
                var user = bsUser.GetById(userId);
                if (user == null)
                {
                    throw new ArgumentException("参数异常，找不到Id=" + userId + "的用户");
                }
                BaseService<Address> bs = new BaseService<Address>(ctx);

                var address = bs.GetAll().AsNoTracking()
                      .FirstOrDefault(e => e.UserId == userId);

                return address != null ? (long?)address.Id : null;
            }
        }

        public AddressDTO[] GetAll()
        {
            using (LuShanTeaContext ctx = new LuShanTeaContext())
            {
                BaseService<Address> bs = new BaseService<Address>(ctx);
                return bs.GetAll()
                      .AsNoTracking()
                      .Include(e => e.User)
                      .Include(e => e.Area)
                      .Include(e => e.Area.City)
                      .Include(e => e.Area.City.Province)
                      .ToList().Select(e => ToDTO(e)).ToArray();
            }
        }

        public bool HasAddressByUser(long userId, long addressId)
        {
            using (LuShanTeaContext ctx = new LuShanTeaContext())
            {
                BaseService<User> bsUser = new BaseService<User>(ctx);
                var user = bsUser.GetById(userId);
                if (user == null)
                {
                    throw new ArgumentException("参数异常，找不到Id=" + userId + "的用户");
                }
                BaseService<Address> bs = new BaseService<Address>(ctx);


                return bs.GetAll().Any(a => a.UserId == userId && a.Id == addressId);
            }
        }

        public AddressDTO GetByAddressId(long addressId)
        {
            using (LuShanTeaContext ctx = new LuShanTeaContext())
            {
                BaseService<Address> bs = new BaseService<Address>(ctx);
                var res = bs.GetById(addressId);
                return res == null ? null : ToDTO(res);
            }
        }

        public void MarkDelete(long addressId)
        {
            using (LuShanTeaContext ctx = new LuShanTeaContext())
            {
                BaseService<Address> bs = new BaseService<Address>(ctx);
                bs.MakeDelete(addressId);
            }
        }

        public void Update(AddressAddNewDTO addressU)
        {
            using (LuShanTeaContext ctx = new LuShanTeaContext())
            {
                BaseService<Address> bs = new BaseService<Address>(ctx);
                var en = bs.GetById(addressU.Id);
                if (en == null)
                {
                    throw new ArgumentException("参数异常，找不到id=" + addressU.Id + "的地址");
                }

                en.AreaId = addressU.AreaId;
                en.PhoneNum = addressU.PhoneNum;
                en.PostEmail = addressU.PostEmail;
                en.ReciverAddress = addressU.ReciverAddress;
                en.ReciverName = addressU.ReciverName;
                en.UserId = addressU.UserId;

                ctx.SaveChanges();
            }
        }

        public AddressDTO[] GetPageAddress(int pageIndex, int pageCount)
        {
            using (LuShanTeaContext ctx = new LuShanTeaContext())
            {
                BaseService<Address> bs = new BaseService<Address>(ctx);

                return bs.GetAll()
                     .AsNoTracking()
                     .Include(e => e.User)
                     .Include(e => e.Area)
                     .Include(e => e.Area.City)
                     .Include(e => e.Area.City.Province)
                     .OrderBy(e => e.CreateDateTime)
                     .Skip((pageIndex - 1) * pageCount)
                     .Take(pageCount)
                     .ToList().Select(e => ToDTO(e)).ToArray();
            }
        }

        public long GetTotalCount()
        {
            using (LuShanTeaContext ctx = new LuShanTeaContext())
            {
                BaseService<Address> bs = new BaseService<Address>(ctx);

                return bs.GetTotalCount();
            }
        }

        public long UpdateAddres(AddressAddNewDTO addressU)
        {
            using (LuShanTeaContext ctx = new LuShanTeaContext())
            {
                BaseService<Address> bs = new BaseService<Address>(ctx);
                var en = bs.GetById(addressU.Id);
                if (en == null)
                {
                    throw new ArgumentException("参数异常，找不到id=" + addressU.Id + "的地址");
                }

                en.AreaId = addressU.AreaId;
                en.PhoneNum = addressU.PhoneNum;
                en.PostEmail = addressU.PostEmail;
                en.ReciverAddress = addressU.ReciverAddress;
                en.ReciverName = addressU.ReciverName;
                en.UserId = addressU.UserId;

                var user = ctx.Users.SingleOrDefault(u => u.Name == "<#临时地址数据#>");

                if (user == null)
                {
                    throw new ArgumentException("数据异常，没找到存储临时收货地址表的用户");
                }

                //判断是否已经修改过
                if (en.UserId != user.Id)
                {
                    en.UserId = user.Id;
                    ctx.Address.Add(en);
                }

                ctx.SaveChanges();

                return en.Id;
            }
        }
    }
}
